import {colorUISdk} from "../../config/mp-sdk";
import {updateCurrentPageShare} from "../../mp-sdk/lib/share";

const app = getApp();

let hasShowedOnce = false;

Page({
    data: {
        scrollTop: 0,
        target: "",
        modalBox: {
            title: '修改',
            qrcode_id: '',
            phone: '',
            backup_phone: '',
            short_message: 0,
            is_privacy: 1,
        },
        userInfo: {
            id: '',
            avatar: '',
            nickname: '',
            carQrcode: [],  // 确保初始化是数组
            wx_notice: 0,
            group_img: '',
            phone: '',
            backup_phone: '',
            is_privacy: 1,
            qrcode_url: '',
            is_agent: '',
            reward_switch: '',
            is_bind: false,
            can_withdraw: 0.00,
            pending_amount: 0.00,
            is_open_distribution: 0,
            reward_title: '',
            reward_text: '',
            reward_money: '',
            agent_tip_text1: "",
            agent_tip_text2: "",
            agent_tip_money1: "0.00",
            agent_tip_money2: "0.00",

        },
        modal: {
            show: false,
            title: '',
            content: ""
        },
        tipModalShow: false,
        tipModalAgentShow: false,
    },

    onLoad() {
        this.getUserInfo();
        /* if (app.userInfo && Object.keys(app.userInfo).length > 0) {
             this.setData({
                 userInfo: app.userInfo
             });
         } else {
             this.getUserInfo();
         }*/
    },
    onShow() {
        if (!hasShowedOnce) {
            hasShowedOnce = true;
            return;  // 第一次进入不执行
        }

        this.getUserInfo();

        // 第二次及以后才执行逻辑
        /* if (app.userInfo && Object.keys(app.userInfo).length > 0) {
             this.setData({
                 userInfo: app.userInfo
             });
         } else {
             this.getUserInfo();
         }*/
    },
    onTip() {
        this.setData({
            tipModalShow: true
        })
    },

    tipText() {
        this.setData({
            tipModalAgentShow: true
        })
    },
    onTipModalClose() {
        this.setData({
            tipModalShow: false
        })
    },
    // 格式化接口返回数据，避免空值错误
    formatUserInfo(data) {
        return {
            id: data.id || '',
            avatar: data.avatar || '',
            nickname: data.nickname || '',
            carQrcode: Array.isArray(data.carQrcode) ? data.carQrcode : [],
            wx_notice: data.wx_notice || 0,
            group_img: data.group_img || '',
            phone: data.phone || '',
            backup_phone: data.backup_phone || '',
            is_privacy: data.is_privacy || 1,
            qrcode_url: data.qrcode_url || '',
            is_bind: data.is_bind || false,
            can_withdraw: data.can_withdraw || 0.00,
            pending_amount: data.pending_amount || 0.00,
            is_open_distribution: data.is_open_distribution || 0,
            reward_title: data.reward_title || 0,
            reward_text: data.reward_text || 0,
            is_agent: data.is_agent || 0,
            reward_money: data.reward_money || 0,
            reward_switch: data.reward_switch || 0,
            agent_tip_text1: data.agent_tip_text1 || '',
            agent_tip_text2: data.agent_tip_text2 || '',
            agent_tip_money1: data.agent_tip_money1 || "0.00",
            agent_tip_money2: data.agent_tip_money2 || "0.00",
        };
    },

    goToBuy() {
        wx.navigateTo({
            url: '/pages/yd_product/home'
        })
    },


    // 拉取用户及二维码列表
    getUserInfo() {
        colorUISdk.request({
            url: 'api/user/info',
            method: 'GET',
            data: {}
        }).then(res => {
            if (res && res.code === 1) {
                this.setUserInfo(res.data);
                // 登录成功后立即更新分享配置
                updateCurrentPageShare();
            } else {
                wx.showToast({title: res.msg || '获取失败', icon: 'none'});
            }
        }).catch(err => {
            console.error(err);
            wx.showToast({title: '系统异常', icon: 'none'});
        });
    },
    setUserInfo(data) {
        this.setData({
            userInfo: this.formatUserInfo(data)
        });
        app.userInfo = this.data.userInfo;
    },
    tapToUrl(e) {
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        });
    },
    changeWxNotice(e) {
        if (e.detail) {
            this.subscribe();
        } else {
            colorUISdk.request({
                url: 'api/user/change_wx_notice',
                method: 'POST',
                data: {
                    wx_notice: 0
                }
            }).then(res => {
                if (res.code === 1) {
                    this.setUserInfo(res.data);
                    wx.showToast({title: res.msg, icon: 'success'});
                } else {
                    wx.showToast({title: res.msg, icon: 'none'});
                }
            });
        }
    },

    subscribe() {
        wx.requestSubscribeMessage({
            tmplIds: ['nGA2V4J7bVeuKS7xiu4RsAsw91BEB45N13sJ_VNpQmQ'],
            success: res => {
                if (res['nGA2V4J7bVeuKS7xiu4RsAsw91BEB45N13sJ_VNpQmQ'] === 'accept') {
                    colorUISdk.request({
                        url: 'api/user/change_wx_notice',
                        method: 'POST',
                        data: {wx_notice: 1}
                    }).then(res => {
                        if (res.code === 1) {
                            this.setUserInfo(res.data);

                            this.setData({
                                modal: {
                                    show: true,
                                    title: '订阅成功',
                                    content: res.msg
                                }
                            });
                        } else {
                            wx.showToast({title: res.msg, icon: 'none'});
                        }
                    });
                }
            }
        });
    },

    toPay(e) {

        colorUISdk.request({
            url: 'api/user/wx_pay',
            method: 'POST',
            data: {}
        }).then(res => {
            if (res.code === 1) {
                const payData = res.data;
                wx.requestPayment({
                    timeStamp: payData.timeStamp,
                    nonceStr: payData.nonceStr,
                    package: payData.package,
                    signType: payData.signType,
                    paySign: payData.paySign,
                    success (paymentRes) {
                        wx.showToast({ title: '支付成功' });
                        // 这里可以做支付成功后的逻辑，比如刷新订单状态
                    },
                    fail (paymentErr) {
                        wx.showToast({ title: '支付失败', icon: 'none' });
                        console.error('支付失败：', paymentErr);
                    }
                });
            } else {
                wx.showToast({ title: res.msg || '下单失败', icon: 'none' });
            }
        }).catch(() => {
            wx.showToast({ title: '系统异常', icon: 'none' });
        });
    },

    getQrCode(e) {
        const qrcode_id = e.currentTarget.dataset.qrcode_id;
        colorUISdk.request({
            url: 'api/user/get_qrcode_details',
            method: 'GET',
            data: {qrcode_id}
        }).then(res => {
            if (res.code === 1) {
                this.setData({
                    modalBox: {
                        title: '修改',
                        qrcode_id: res.data.id,
                        phone: res.data.phone,
                        backup_phone: res.data.backup_phone,
                        short_message: res.data.short_message,
                        is_privacy: res.data.is_privacy,
                    },
                    target: 'drawer'  // 打开底部弹窗
                });
            } else {
                wx.showToast({title: res.msg, icon: 'none'});
            }
        }).catch(() => {
            wx.showToast({title: '系统异常', icon: 'none'});
        });
    },

    unbindQrCode(e) {
        const qrcode_id = e.currentTarget.dataset.qrcode_id;
        wx.showModal({
            title: '解绑挪车码',
            content: '解绑后,再次绑定需要重新扫码哦~',
            success: res => {
                if (res.confirm) {
                    colorUISdk.request({
                        url: 'api/user/unbind_qrcode',
                        method: 'POST',
                        data: {qrcode_id}
                    }).then(res => {
                        if (res.code === 1) {
                            this.setUserInfo(res.data);
                            wx.showToast({title: '解绑成功'});
                        } else {
                            wx.showToast({title: res.msg, icon: 'none'});
                        }
                    }).catch(() => {
                        wx.showToast({title: '系统异常', icon: 'none'});
                    });
                }
            }
        });
    },

    setQrcode(e) {
        if (e.detail.confirm) {
            colorUISdk.request({
                url: 'api/user/update_qrcode',
                method: 'POST',
                data: {from: this.data.modalBox}
            }).then(res => {
                if (res.code === 1) {
                    this.setData({
                        modalBox: {
                            title: '修改',
                            qrcode_id: res.data.id,
                            phone: res.data.phone,
                            backup_phone: res.data.backup_phone,
                            short_message: res.data.short_message,
                            is_privacy: res.data.is_privacy,
                        },
                        target: ''  // 关闭弹窗
                    });
                    wx.showToast({title: '修改成功'});
                } else {
                    wx.showToast({title: res.msg, icon: 'none'});
                }
            }).catch(() => {
                wx.showToast({title: '系统异常', icon: 'none'});
            });
        }
    },

    onInputChange(e) {
        const field = e.currentTarget.dataset.field;
        const value = e.detail.value;
        this.setData({[`modalBox.${field}`]: value});
    },

    onSwitchChange(e) {
        const field = e.currentTarget.dataset.field;
        const value = e.detail ? 1 : 0;
        this.setData({[`modalBox.${field}`]: value});
    },


    tapToHelp() {
        wx.navigateTo({
            url: '/pages/yd_help/home',
        })
    },
    //微信群
    tapToAgentList() {
        wx.navigateTo({
            url: '/pages/yd_agent_list/home',
        })
    },

    //我的账户
    tapToAccount() {
        wx.navigateTo({
            url: '/pages/yd_account/home',
        })
    },

    //我的代理
    tapToAgent() {
        wx.navigateTo({
            url: '/pages/yd_agent/home',
        })
    },

    //微信群
    tapToGroup() {
        wx.previewImage({
            urls: [this.data.userInfo.group_img],
            current: this.data.userInfo.group_img,
            showmenu: true,
        })
    },
    goToTry() {
        wx.navigateTo({
            url: '/pages/yd_test/home',
        })
    },
    goToWithdrawList() {
        wx.navigateTo({
            url: '/pages/yd_order/home?status=2'  // 可提现
        });
    },
    onPageScroll(e) {
        this.setData({scrollTop: e.scrollTop});
    },
});
